<?php

namespace Fendx\Doctrine;

use Doctrine\ORM\EntityManager;

/**
 * Override EntityManagerOverride
 *
 * @Author  gary
 *
 * @return EntityManager
 */
class EntityManagerOverride
{
    private $em = null;
    private $db = null;

    public function __construct(EntityManager $em, \Fendx\Db\EntityManager $db) {
        $this->em = $em;
        $this->em->clear();
        $this->db = $db;
    }

    public function getRepository($tableName = ''): EntityRepositoryOverride {
        return new EntityRepositoryOverride($this->em->getRepository($tableName), $this->em, $this->db);
    }

    public function __call($name, $arguments) {
        return $this->em->$name(...$arguments);
    }

    public function persist($entity) {
        $this->em->persist($entity);
    }

    public function flush($entity = null) {
        $startTime = microtime(true);

        $this->em->flush($entity);
        //debug open will record more
        if (\Fendx\Debug::isDebug()) {
            $sql = "flush <br />" . var_export($this->em->getUnitOfWork()->getIdentityMap(), true);
            $this->db->appendSqlInfo($sql, [(string) $entity], $startTime);
        }
    }

    public function __destruct() {
        $this->em = null;
        $this->db = null;
    }
}
